package com.fgs.common.permission;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;

import com.fgs.common.interf.OnDialogClickListener;
import com.fgs.common.widget.PermissionDialog;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.lang.ref.WeakReference;

/**
 * @author fgs
 * @date 2020/6/12
 * @description
 **/
public class PermissionHelper implements IPermission {

    @Override
    public boolean checkPermissions(FragmentActivity activity, OnPermissionCheckResult onPermissionCheckResult, String... permissions) {

        RxPermissions rxPermissions = new RxPermissions(activity);
        rxPermissions.requestEachCombined(permissions).subscribe(permission -> {
            if (permission.granted) {
                if (onPermissionCheckResult != null)
                    onPermissionCheckResult.grantedResult();
            } else if (permission.shouldShowRequestPermissionRationale) {
                if (onPermissionCheckResult != null)
                    onPermissionCheckResult.shouldShowRequestPermissionRationale();
            } else {
                if (onPermissionCheckResult != null)
                    onPermissionCheckResult.grantedForbidResult();
            }
        });

        return false;
    }

    @Override
    public boolean checkPermissions(Context context, String permission, OnPermissionCheckResult onPermissionCheckResult) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            int checkPermissionResult = context.checkSelfPermission(permission);
            if (checkPermissionResult == PackageManager.PERMISSION_GRANTED) {
                if (onPermissionCheckResult != null) {
                    onPermissionCheckResult.grantedResult();
                }
                return true;
            } else {
                showPermissionInstructionDialog(context, permission, onPermissionCheckResult);
            }
        } else {
            checkPermissions((FragmentActivity) context, onPermissionCheckResult, permission);
        }
        return false;
    }

    @Override
    public void showPermissionTipDialog(Context context, String permission) {
        new MaterialDialog.Builder(context)
                .content(getPermissionTip(permission))
                .positiveText("确定")
                .negativeText("取消")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (Build.VERSION.SDK_INT >= 9) {
                            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
                        } else if (Build.VERSION.SDK_INT <= 8) {
                            intent.setAction(Intent.ACTION_VIEW);
                            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
                            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
                        }
                        try {
                            context.startActivity(intent);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                })
                .show();
    }

    private void showPermissionInstructionDialog(Context context, String permission, OnPermissionCheckResult onPermissionCheckResult) {
        if (TextUtils.isEmpty(permission)) return;
        WeakReference<Context> weakReference = new WeakReference<>(context);
        Context weakContext = weakReference.get();

        String instruction = getPermissionTip(permission);
        new PermissionDialog(weakContext, new OnDialogClickListener() {
            @Override
            public void onPositiveClick() {
                if (onPermissionCheckResult != null)
                    checkPermissions((FragmentActivity) weakContext, onPermissionCheckResult, permission);
            }

            @Override
            public void onNegativeClick(boolean isForce) {
                if (onPermissionCheckResult != null)
                    onPermissionCheckResult.shouldShowRequestPermissionRationale();
            }
        })
                .setContent(instruction)
                .show();
    }

    private String getPermissionTip(String permission) {
        if (TextUtils.isEmpty(permission)) return "";
        String instruction;
        if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
            instruction = "皓俊通网络货运服务系统需要打开定位权限，以便获取位置信息";
        }else if (permission.equals("android.permission.ACCESS_BACKGROUND_LOCATION")) {
            instruction = "皓俊通网络货运服务系统需要打开后台定位权限，以便实时获取位置信息\n打开流程：皓俊通网络货运服务系统应用下：权限->位置信息(定位)->始终允许\n或弹窗中点击在设置中允许->始终允许";
        } else if (permission.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            instruction = "皓俊通网络货运服务系统需要打开存储权限，以便访问相册";
        } else if (permission.equals(Manifest.permission.CAMERA)) {
            instruction = "皓俊通网络货运服务系统需要打开您的相机，用于上传司机和车辆证件照片，其他照片，扫码和更换头像";
        } else if (permission.equals(Manifest.permission.READ_PHONE_STATE)) {
            instruction = "皓俊通网络货运服务系统需要打开电话权限，以便获取设备识别码，使软件对应手机的唯一性";
        } else {
            instruction = permission;
        }
        return instruction;
    }

//    public void showOpenPermissionSettingDialog(Context context,String permission) {
//        new MaterialDialog.Builder(context)
//                .content(getPermissionTip(permission))
//                .positiveText("确定")
//                .negativeText("取消")
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        Intent intent = new Intent();
//                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                        if (Build.VERSION.SDK_INT >= 9) {
//                            intent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
//                            intent.setData(Uri.fromParts("package", context.getPackageName(), null));
//                        } else if (Build.VERSION.SDK_INT <= 8) {
//                            intent.setAction(Intent.ACTION_VIEW);
//                            intent.setClassName("com.android.settings", "com.android.settings.InstalledAppDetails");
//                            intent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName());
//                        }
//                        try {
//                            context.startActivity(intent);
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
//                    }
//                })
//                .show();
//    }

}
